package ynu.edu.achitecturework.service;

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class YsService {

    private final RestTemplate restTemplate;
    private String accessToken;
    private long tokenExpireTime;

    public YsService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void login() {
        String url = "http://42.193.14.241:7000/ysapi/subAccount/getToken";

        Map<String, String> requestBody = Map.of(
                "accountId", "1ca7f0ab24ba41b291346347ec30140e"
        );

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);

        ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);

        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            Map<String, Object> data = (Map<String, Object>) response.getBody().get("data");
            this.accessToken = (String) data.get("accessToken");
            this.tokenExpireTime = (long) data.get("expireTime");
        }
    }

    public String capturePhoto() {
        if (accessToken == null && System.currentTimeMillis() > tokenExpireTime) {
            login();
        }

        String url = "https://open.ys7.com/api/lapp/device/capture";

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("accessToken", accessToken);
        params.add("deviceSerial", "AB9831171");
        params.add("channelNo", "1");
        params.add("quality", "3");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

        ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);

        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            Map<String, String> data = (Map<String, String>) response.getBody().get("data");
            return data.get("picUrl");
        }

        return null;
    }
    public String getAccessToken() {
        if (accessToken == null && System.currentTimeMillis() > tokenExpireTime) {
            login();
        }
        return accessToken;
    }
}